<template>
  <base-layout
    :dialogVisible="dialogVisible"
    :dialogTitle="dialogTitle"
    @dialog-close="dialogClose"
    :visibleContent2="true"
  >
    <template #searchPanel>
      <el-form
        :inline="true"
        ref="fromdata1"
        :model="fromdata"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">入库单基础信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="入库编号:" prop="inStorageCode">
              <el-input clearable readonly v-model="fromdata.inStorageCode" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库门店:" prop="inStoreId">
              <Job-shop
                v-model="fromdata.storeId"
                placeholder="入库门店"
                :defaultStoreId="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库仓库:" prop="storageId">
              <el-select
                clearable
                style="width: 200px"
                v-model="fromdata.storageId"
                placeholder="仓库"
              >
                <el-option
                  v-for="item in storageList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商:" prop="supplierId">
              <el-select
                clearable
                filterable
                v-model="fromdata.supplierId"
                placeholder="供应商"
                class="w-100"
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.supplierName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期:" prop="receiptsTime">
              <el-date-picker
                value-format="yyyy-MM-dd hh:mm:ss"
                v-model="fromdata.receiptsTime"
                type="datetime"
                style="width: 200px"
                disabled="disabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库类型:" prop="inStorageType">
              <el-select
                clearable
                style="width: 200px"
                v-model="fromdata.inStorageType"
              >
                <el-option
                  v-for="item in dict['入库类型']"
                  :key="item.index"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="!addInventoryShow">
            <el-form-item :label="label" prop="workOrderCode">
              <el-input
                clearable
                v-model.number="fromdata.workOrderCode"
                @blur="findSourceCode"
                @keyup.native="$event.target.value = $event.target.value.replace(/^\s+|\s+$/gm,'')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库负责人:" prop="userName">
              <el-input
                clearable
                v-model="fromdata.userName"
                @focus="employeeFocus"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人联系方式:" prop="phone">
              <el-input clearable v-model.number="fromdata.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库备注:" prop="remark">
              <el-input
                type="textarea"
                :rows="6"
                placeholder=""
                v-model="fromdata.remark"
                style="width: 600px"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="false"
        :hide-required-asterisk="true"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
        class="insuranceForm"
      >
        <el-row>
          <el-col :span="22">入库配件列表</el-col>
          <el-col :span="2" v-if="addInventoryShow">
            <el-button icon="el-icon-plus" type="primary" @click="addInventory"
              >添加入库配件</el-button
            >
          </el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <data-table
            :value="fromdata.partsList"
            :total-count="fromdata.partsList.length"
            :has-action="true"
            :table-column-attributes="tableColumnAttributes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :width="160"
            :localPage="true"
          >
            <template #action="{ row }">
              <i
                class="el-icon-delete"
                title="删除"
                style="color: red; margin-left: 20px; cursor: pointer"
                @click="deleteLochost(row)"
              ></i>
            </template>
            <template #allNum>
              <el-col :span="8" v-if="allMount">
                <span
                  style="line-height: 10px; text-align: left; color: #606266"
                  >{{ allLabel
                  }}<span style="color: #f40; font-size: 20px"
                    >￥{{ allMount }}</span
                  ></span
                >
              </el-col>
              <el-col :span="8" v-if="allMount1">
                <span
                  style="line-height: 10px; text-align: left; color: #606266"
                  >{{ allLabel1
                  }}<span style="color: #f40; font-size: 20px">{{
                    allMount1
                  }}</span></span
                >
              </el-col>
            </template>
          </data-table>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel2>
      <el-row>
        <el-col :span="24" align="right" justify="center">
          <el-col :span="24">
            <span style="line-height: 10px; text-align: left; color: #606266"
              >入库总金额：<span
                style="color: #f40; font-size: 20px"
                v-if="allMount"
                >￥{{ allMount }}</span
              ></span
            >
          </el-col>
          <el-col :span="24" style="margin-top: 20px">
            <el-button type="success" @click="saveUpdate">新建入库单</el-button>
          </el-col>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <SelectAccessories
        :storageId="fromdata.storeId"
        v-if="showSelect"
        :supplierId="fromdata.supplierId"
        @partsList="partsList"
      />
      <EmployeeTable
        v-if="showEmployeeTable"
        @roleIdListSelectCheck="employeListSelectCheck"
        :checkList="[fromdata.manageUserName]"
      />
    </template>
  </base-layout>
</template>
<script>
import baseMixin from '@/mixins/base'
import {
  update,
  add,
  getFindById,
  getStorageCode,
  findSourceCode,
} from '@/api/after-sale/storehouseManage/inOfStockManage'
import { findByStore } from '@/api/after-sale/storehouseManage/warehouseManage'
import { getSupplierByStorId } from '@/api/after-sale/systemManage/supplier'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import SelectAccessories from '@/components/SelectAccessories/index' //导入组件
import EmployeeTable from '../../systemManage/store/components/EmployeeTable'
import {
  findByStoreIdAndStorageId,
  getDetail as getFindPosDetail,
} from '@/api/after-sale/storehouseManage/positionManage'
import store from '@/store'
export default {
  components: {
    SelectAccessories,
    EmployeeTable,
  },
  mixins: [
    baseMixin({
      addData: add,
      updateData: update,
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  watch: {
    'fromdata.storeId': function (value) {
      if (value) {
        this.getWareHouse(value)
        this.getSupplierByStorId(value)
      } else {
        this.getWareHouse(store.state.user.entryStore)
        this.getSupplierByStorId(store.state.user.entryStore)
      }
    },
    'fromdata.storageId': function (value) {
      if (value) {
        this.findByStoreIdAndStorageId(this.fromdata.storeId, value)
      }
    },
    'fromdata.inStorageType': function (value) {
      if (value === '采购入库') {
        this.addInventoryShow = false
        this.label = '采购编号:'
      } else if (value === '退料入库') {
        this.addInventoryShow = false
        this.label = '工单编号:'
      } else if (value === '调拨入库') {
        this.addInventoryShow = false
        this.label = '调拨编号:'
      } else {
        this.addInventoryShow = true
      }
    },
    'fromdata.partsList': {
      handler(value) {
        this.sumAllMount()
      },
      deep: true,
    },
  },
  data() {
    return {
      label: '来源单号',
      fromdata: {
        storageId: null,
        partsList: [],
        id: null,
        receiptsTime: parseTimeToYMDHMS(new Date()),
        workOrderCode: null
      },
      rules: {},
      dialogImageUrl: '',
      imageDialogVisible: false,
      dict: [],
      showSelect: false, // 是否展示配件组件
      showEmployeeTable: false, //  是否展示员工组件
      positionList: [], // 仓位列表
      allMount: null,
      allLabel: '配件总金额：',
      allMount1: null,
      addInventoryShow: true, // 是否现实添加入库配件按钮
      allLabel1: '配件总数：',
      tableColumnAttributes: [
        { name: '配件编号', value: 'partsCode', type: 'text' },
        { name: '配件名称', value: 'partsName', type: 'text' },
        { name: '配件类别', value: 'partsType', type: 'text' },
        { name: '配件单位', value: 'partsUnit', type: 'text' },
        {
          name: '配件仓位',
          filterable: true,
          value: 'storageSiteName',
          type: 'select',
          valueId: 'storageSiteId',
          action: this.storageSiteChange,
          options: this.findByStoreIdAndStorageId,
        },
        { name: '仓位编号', value: 'storageSiteCode', type: 'text' },
        {
          name: '入库数量',
          value: 'inStorageNum',
          type: 'inputNumber',
          action: function (row) {
            row.amount = row.inStorageNum * row.storagePrice
          },
        },
        { name: '库存数量', value: 'allNum', type: 'text' },
        { name: '内置个数', value: 'internalNum', type: 'text' },
        { name: '现有库存', value: 'alreadyNum', type: 'text' },
        { name: '可增加库存', value: 'allNum', type: 'text' },
        { name: '采购成本', value: 'purchasePrice', type: 'text' },
        {
          name: '销售价',
          value: 'storagePrice',
          type: 'input',
          widht: '100px',
          action: function (row) {
            row.amount = row.inStorageNum * row.storagePrice
          },
        },
        { name: '总金额', value: 'amount', type: 'text' },
      ],
      storageList: [],
      rules: {
        receiptsTime: [
          { required: true, message: '请选择单据日期', trigger: 'change' },
        ],
        storageId: [
          { required: true, message: '请选择盘点仓库', trigger: 'blur' },
        ],
        inStorageType: [
          { required: true, message: '请选入库类型', trigger: 'change' },
        ],
      },
      supplierList: [], // 供应商列表
    }
  },
  methods: {
    // 动态计算表格总和
    sumAllMount() {
      this.allMount = null
      this.allMount1 = null
      if (this.fromdata.partsList) {
        this.fromdata.partsList.forEach((e) => {
          if (e.amount) {
            this.allMount += Number.parseFloat(e.amount)
          }
          if (e.inStorageNum) {
            this.allMount1 += Number.parseInt(e.inStorageNum)
          }
        })
      }
    },
    //删除临时配件
    deleteLochost(row) {
      this.fromdata.partsList = this.fromdata.partsList.filter(
        (e) => e.id != row.id
      )
    },
    // 根据来源单号查询配件列表
    async findSourceCode() {
      if (this.fromdata.workOrderCode == null || this.fromdata.workOrderCode == '') {
        return;
      }
      let { data } = await findSourceCode(
        this.fromdata.inStorageType,
        this.fromdata.workOrderCode
      )
      data.forEach((e) => {
        e.num = e.inStorageNum
      })
      this.fromdata.partsList = data.filter((e) => e)
    },
    async storageSiteChange(row) {
      getFindPosDetail(row.storageSiteId).then((res) => {
        let { data } = res
        for (let i in this.fromdata.partsList) {
          if (this.fromdata.partsList[i].id === row.id) {
            // this.$set(this.fromdata.partsList[i], 'allNum', data.num)
            // this.$set(this.fromdata.partsList[i], 'alreadyNum', data.alreadyNum)
            this.$set(
              this.fromdata.partsList[i],
              'storageSiteCode',
              data.storageSiteCode
            )
          } else {
          }
        }
      })
    },
    // 获取仓位信息
    async findByStoreIdAndStorageId(storeId, storageId) {
      let { data } = await findByStoreIdAndStorageId(storeId, storageId)
      data.forEach((e) => {
        e.value = e.storageSiteName
      })
      this.tableColumnAttributes[4].options = data
      this.positionList = data
    },
    // 获取仓库
    async getWareHouse(id) {
      let { data } = await findByStore(id)
      this.storageList = data
    },
    // 打开配件选择
    addInventory() {
      this.showSelect = true
      this.showEmployeeTable = false
      this.handleDataInsert('配件选择')
    },
    //打开员工选择列表
    employeeFocus() {
      this.showSelect = false
      this.showEmployeeTable = true
      this.handleDataInsert('管理人员列表')
    },
    //员工选择
    employeListSelectCheck(select) {
      this.fromdata.userName = select[0].userName
      this.fromdata.phone = select[0].phone
      this.fromdata.userId = select[0].id
      this.dialogClose()
    },
    async saveUpdate() {
      this.$refs['fromdata1'].validate((valid) => {
        if (valid) {
          this.fromdata.amount = this.allMount
          this.handleDataUpdate(this.fromdata)
          this.closeRouter('/partsStock/partsStockManage/inOfStockManage')
        }
      })
    },
    async detail(id) {
      let { data } = await getFindById(id)
      this.fromdata = data
    },
    async getStorageCode() {
      let { data } = await getStorageCode()
      this.fromdata.inStorageCode = data
    },
    // 获取供应商
    async getSupplierByStorId(storeId) {
      let { data } = await getSupplierByStorId(storeId, '配件供应商')
      this.supplierList = data
    },
    // 选择配件
    partsList(value) {
      if (value.length > 0) {
        value.forEach((e) => {
          let index = true
          this.fromdata.partsList.forEach((g) => {
            if (e.id === g.id) {
              index = false
            }
          })
          if (index) {
            let { ...data } = {
              ...e,
              partsUnit: e.unit,
              partsId: e.id,
              partsType: e.partsDictValue,
            }
            this.fromdata.partsList.push(data)
          }
        })
      }
      this.dialogClose()
    },
  },
  mounted() {
    this.dict = getDict(['入库类型'])
    let id = this.$route.query.id
    let from = this.$route.query.from
    if (id) {
      this.fromdata.id = id
      this.detail(id)
    } else {
      // 采购入库跳过来
      if (from) {
        this.fromdata = { ...from }
        ;(this.fromdata.receiptsTime = parseTimeToYMDHMS(new Date())),
          this.findSourceCode()
      }
      this.getStorageCode()
    }
  },
}
</script>
<style lang="scss" scoped></style>
